﻿using System;
using System.Collections.Generic;
using System.Text;
using com.tiyma.model;
using System.Data;
using com.tiyma.common;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
namespace com.tiyma.data
{
    public class BookDao
    {
        /// <summary>
        /// 添加站点信息
        /// </summary>
        /// <param name="i_site_name"></param>
        /// <param name="i_site_domain"></param>
        /// <param name="i_pr"></param>
        /// <param name="i_email"></param>
        /// <returns></returns>
        public Consts.ResultType AddSite(string i_site_name, string i_site_domain, int i_pr, string i_email)
        {
            string t_str_sql = string.Format("select count(siteDomain) totalCount from tbUserSite where siteDomain='{0}'", i_site_domain);

            int t_exists = 0;
            try
            {
                DataSet ds = DBHelper.Query(t_str_sql);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(ds.Tables[0].Rows[0]["totalCount"].ToString(), out t_exists))
                        t_exists = 0;
                }
                if (t_exists > 0)
                    return Consts.ResultType.Exists;

                t_str_sql = string.Format("insert into tbUserSite(siteName,siteDomain,siteEmail,sitePr)values('{0}','{1}','{2}',{3})",
                    i_site_name, i_site_domain, i_email, i_pr);

                int t_ret = DBHelper.ExecuteSql(t_str_sql);

                if (t_ret > 0)
                    return Consts.ResultType.Successed;

                return Consts.ResultType.Faild;

            }
            catch (Exception ex)
            {
                throw new DataException("添加站点信息时候", ex);
            }
        }


        /// <summary>
        /// 下架书架小说
        /// </summary>
        /// <param name="i_user_id"></param>
        /// <param name="i_book_name_list"></param>
        /// <returns></returns>
        public int DownBook(long i_user_id, string i_book_name_list)
        {
            string t_str_sql = string.Format("delete from tbUserBook where userId={0} and bookName in({1})", i_user_id, i_book_name_list);

            try
            {
                return DBHelper.ExecuteSql(t_str_sql);
            }
            catch (Exception ex)
            {
                throw new DataException("下架书架小说失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 获取用户书架图书
        /// </summary>
        /// <param name="i_user_id"></param>
        /// <returns></returns>
        public List<string> GetUserBook(long i_user_id)
        {
            string t_str_sql = string.Format("select bookName from tbUserBook where userId={0}", i_user_id);

            List<string> t_list = new List<string>();
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        string t_book_name = reader["bookName"].ToString();

                        t_list.Add(t_book_name);
                    }
                }

                 return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取用户书架图书失败", ex);
            }
        }

        /// <summary>
        /// 添加书架
        /// </summary>
        /// <param name="i_user_id"></param>
        /// <param name="i_book_name"></param>
        /// <returns></returns>
        public Consts.ResultType AddBookCase(long i_user_id, string i_book_name)
        {
            string t_str_sql = string.Format("select count(bookName) totalCount from tbUserBook where bookName='{0}'", i_book_name);

            int t_exists_count = 0;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        if (!int.TryParse(reader["totalCount"].ToString(), out t_exists_count))
                            t_exists_count = 0;
                    }
                }

                if (t_exists_count > 0)
                    return Consts.ResultType.Exists;

                t_str_sql = string.Format("insert into tbUserBook(userId,bookName)values({0},'{1}')", i_user_id, i_book_name);

                int t_ret = DBHelper.ExecuteSql(t_str_sql);

                if (t_ret > 0)
                    return Consts.ResultType.Successed;

                return Consts.ResultType.Faild;

            }
            catch (Exception ex)
            {
                throw new DataException("添加书架图书失败", ex);
            }

      
        }

        /// <summary>
        /// 获取榜单数据
        /// </summary>
        /// <param name="i_type"></param>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public List<BookInfo> GetTopBook(int i_type,int i_count)
        {
            string t_str_sql = string.Format("select t.bookid,t.bookname,t.authorname,t.lastupdatechapterid,t.lastupdatechaptername,t.lastupdatetime,t.siteId,t.siteName from tbbook t,tbbookclick b where a.bookId=b.bookId", i_count);
           
            BookInfo t_book = null;

            List<BookInfo> t_list = null;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    t_list = new List<BookInfo>();

                    while (reader.Read())
                    {
                        t_book = new BookInfo();
                        t_book.BookId = reader["bookid"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.AuthorName = reader["authorname"].ToString();
                        t_book.LastUpdateChapterId = reader["lastupdatechapterid"] == DBNull.Value ? "0" :reader["lastupdatechapterid"].ToString();
                        t_book.LastUpdateChapterName = reader["lastupdatechaptername"] == DBNull.Value ? string.Empty : reader["lastupdatechaptername"].ToString();
                        t_book.SiteId =Convert.ToInt32( reader["siteId"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();

                        t_list.Add(t_book);
                    }
                }

                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("查询热门搜索失败", ex);
            }
        }

        /// <summary>
        /// 获取章节信息
        /// </summary>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        public ChapterInfo GetChapterInfo(long i_chapter_id, int i_site_id, out SiteInfo o_site_info,Consts.ChapterType i_chapter_type)
        {
            try
            {
                o_site_info = null;

                string t_sql = string.Empty;

                if (i_chapter_type == Consts.ChapterType.reader)
                {
                   string  t_table_name = "tbchapter";
                    t_sql = string.Format("select chapterName,chapterUrl,bookId,bookName,updateTime,preChapterId,nextChapterId,isDownLoad from {0} where chapterId={1}", t_table_name, i_chapter_id);
                }
                else
                {
                    o_site_info = GetTableName(i_site_id);

                    if (o_site_info == null)
                        return null;

                    string t_table_name = o_site_info.TableName;

                    t_sql = string.Format("select chapterName,chapterUrl,bookId,bookName,updateTime,preChapterId,nextChapterId,0 isDownLoad from {0} where chapterId={1}", t_table_name, i_chapter_id);
                }

            

                ChapterInfo t_chapter = null;
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_sql))
                {
                    while (reader.Read())
                    {
                        t_chapter = new ChapterInfo();
                        t_chapter.SiteId = i_site_id;
                        t_chapter.ChapterId = i_chapter_id.ToString();
                        t_chapter.ChapterName = reader["chapterName"].ToString();
                        t_chapter.ChapterUrl = reader["chapterUrl"].ToString();
                        t_chapter.BookId = reader["bookId"].ToString();
                        t_chapter.BookName = reader["bookName"].ToString();
                        t_chapter.PreChapterId = reader["preChapterId"].ToString();
                        t_chapter.NextChapterId = reader["nextChapterId"].ToString();
                        t_chapter.IsDownLoad =Convert.ToInt32( reader["isDownLoad"].ToString());
                        break;
                    }
                }

                return t_chapter;

            }
            catch (Exception ex)
            {
                throw new DataException("获取章节信息失败", ex);
            }
        }

        /// <summary>
        /// 获取表名
        /// </summary>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        public SiteInfo GetTableName(int i_site_id)
        {
            string t_sql = string.Format("select tbName,siteName,siteEnconding,chapterContentReg,chapterContentFilter from tbBookSite where siteId={0}", i_site_id);

            SiteInfo t_site_info = null;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_sql))
                {
                    while (reader.Read())
                    {
                        t_site_info = new SiteInfo();
                        t_site_info.TableName = reader["tbName"].ToString();
                        t_site_info.SiteName = reader["siteName"].ToString();
                        t_site_info.ChapterContentReg = reader["chapterContentReg"].ToString();
                        t_site_info.ChapterContentFilter = reader["chapterContentFilter"].ToString();
                        t_site_info.SiteEnconding = reader["siteEnconding"].ToString();
                        break;
                    }
                }

                return t_site_info;
            }
            catch (Exception ex)
            {
                throw new DataException("获取表名失败", ex);
            }
        }



        /// <summary>
        /// 获取推荐小说失败
        /// </summary>
        /// <param name="i_book_id_list"></param>
        /// <returns></returns>
        public List<BookInfo> GetRemcommendBook(string i_book_id_list)
        {
            string t_str_sql = string.Format("select bookId,bookName,iconUrl,siteId from tbbook where bookId in({0})", i_book_id_list);
            BookInfo t_book=null;
            List<BookInfo> t_list = new List<BookInfo>();
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    t_list = new List<BookInfo>();

                    while (reader.Read())
                    {
                        t_book = new BookInfo();
                        t_book.BookId = reader["bookid"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.ICONUrl = reader["ICONUrl"] == DBNull.Value ? "" : reader["ICONUrl"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["siteId"].ToString());

                        t_list.Add(t_book);
                    }
                }

                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取推荐小说失败", ex);
            }
        }

        /// <summary>
        /// 获取最新更新小说
        /// </summary>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public List<BookInfo> GetLastUpdateBook(int i_count)
        {
            string t_str_sql = string.Format("select top {0} t.bookid,t.bookname,t.authorname,t.lastupdatechapterid,t.lastupdatechaptername,t.lastupdatetime,t.siteId,t.siteName,t.CategoryName from tbbook t order by lastupdatetime desc", i_count);
          
            BookInfo t_book = null;

            List<BookInfo> t_list = null;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    t_list = new List<BookInfo>();

                    while (reader.Read())
                    {
                        t_book = new BookInfo();
                        t_book.BookId = reader["bookid"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.AuthorName = reader["authorname"].ToString();
                        t_book.LastUpdateChapterId = reader["lastupdatechapterid"] == DBNull.Value ? "0" : reader["lastupdatechapterid"].ToString();
                        t_book.LastUpdateChapterName = reader["lastupdatechaptername"] == DBNull.Value ? string.Empty : reader["lastupdatechaptername"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["siteId"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();
                        t_book.BookCategory = reader["CategoryName"].ToString();
                        t_book.LastUpdateTime = reader["lastupdatetime"] == DBNull.Value ? DateTime.Now.AddHours(-1) : Convert.ToDateTime(reader["lastupdatetime"].ToString());

                        t_list.Add(t_book);
                    }
                }

                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取最新更新小说失败", ex);
            }
            
        }

        /// <summary>
        /// 获取小说信息
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="o_chapter_list"></param>
        /// <returns></returns>
        public BookInfo GetBookInfo(long i_book_id, out List<ChapterInfo> o_chapter_list)
        {
            string t_str_sql = string.Format("select bookName,authorName,categoryName,iconUrl,description,lastUpdateChapterId,lastUpdateChapterName,lastUpdateTime,siteId, siteName,chapterCount,status,isDownLoad from tbbook where bookId={0}", i_book_id);
            o_chapter_list = new List<ChapterInfo>();
            BookInfo t_book = null;
            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql);
                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow reader in t_ds.Tables[0].Rows)
                    {
                        t_book = new BookInfo();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.AuthorName = reader["authorName"].ToString();
                        t_book.BookCategory = reader["categoryName"].ToString();
                        t_book.ICONUrl = reader["iconUrl"].ToString();
                        t_book.Description = reader["description"].ToString();
                        t_book.LastUpdateChapterId = reader["lastUpdateChapterId"] == DBNull.Value ? "0" : reader["lastUpdateChapterId"].ToString();
                        t_book.LastUpdateChapterName = reader["lastUpdateChapterName"] == DBNull.Value ? "" : reader["lastUpdateChapterName"].ToString();
                        t_book.LastUpdateTime = reader["lastUpdateTime"] == DBNull.Value ? DateTime.Now.AddHours(-1) : Convert.ToDateTime(reader["lastUpdateTime"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();
                        t_book.BookChapterCount = reader["chapterCount"] == DBNull.Value ? 0 : Convert.ToInt32(reader["chapterCount"].ToString());
                        t_book.SiteId = reader["siteId"] == null ? 0 : Convert.ToInt32(reader["siteId"].ToString());
                        t_book.Status = reader["status"].ToString();
                        t_book.IsDownLoad = (reader["isDownLoad"] == DBNull.Value || string.IsNullOrEmpty(reader["isDownLoad"].ToString())) ? 0 : Convert.ToInt32(reader["isDownLoad"].ToString());
                        break;
                    }
                }
               

                if (t_book == null)
                    return null;

                t_str_sql = string.Format("select chapterId,chapterName,isDownLoad from tbchapter where bookId={0} order by chapterId", i_book_id);
                

                ChapterInfo t_chapter = null;

                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while(reader.Read())
                    {
                        t_chapter = new ChapterInfo();
                        t_chapter.ChapterId = reader["chapterId"].ToString();
                        t_chapter.ChapterName = reader["chapterName"].ToString();
                        t_chapter.IsDownLoad = Convert.ToInt32(reader["isDownLoad"].ToString());
                        o_chapter_list.Add(t_chapter);
                    }
                }

                return t_book;
 
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说信息失败", ex);
            }
        }

        /// <summary>
        /// 获取小说名称
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public string GetBookName(string i_book_id)
        {
            string t_str_sql = string.Format("select bookName from tbbook where bookId={0}", i_book_id);

            string t_book_name = string.Empty;

            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        t_book_name = reader["bookName"].ToString();
                        break;
                    }
                }
                return t_book_name;
            }
            catch (Exception ex)
            {
                LogHelper.Error("生产最新更新列表失败" + ex.ToString());
                return string.Empty;

            }
        }

        /// <summary>
        /// 获取最新更新小说 14条小说
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetLastUpdateBook()
        {
            string t_str_sql = string.Format("select top 14 t.bookid,t.bookname,t.authorname,t.lastupdatechapterid,t.lastupdatechaptername,t.ChapterCount,t.lastupdatetime,t.siteId,t.siteName,t.CategoryName,status,isDownLoad from tbbook t where isDownload={0} order by t.lastupdatetime desc ", Consts.ExistChapterContent);
          
            List<BookInfo> t_list = new List<BookInfo>();

            BookInfo t_book = null;

            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        if (reader["lastupdatetime"] == DBNull.Value || string.IsNullOrEmpty(reader["lastupdatetime"].ToString()))
                            continue;
                        t_book = new BookInfo();
                        t_book.BookCategory = reader["CategoryName"].ToString().Trim().Length == 2 ? reader["CategoryName"].ToString().Trim() + "小说" : reader["CategoryName"].ToString().Trim();
                        t_book.BookId = reader["bookid"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.AuthorName = reader["authorname"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["siteId"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();
                        t_book.LastUpdateChapterId = reader["lastupdatechapterid"].ToString();
                        t_book.LastUpdateChapterName = reader["lastupdatechaptername"].ToString();
                        t_book.LastUpdateTime = Convert.ToDateTime(reader["lastupdatetime"].ToString());
                        t_book.BookChapterCount = GetChapterCount(Convert.ToInt32(reader["chapterCount"].ToString()), reader["lastupdatechaptername"].ToString());
                        t_book.Status = reader["status"].ToString();
                        t_book.IsDownLoad = (reader["IsDownLoad"]==DBNull.Value || string.IsNullOrEmpty(reader["IsDownLoad"].ToString()))?0: Convert.ToInt32( reader["IsDownLoad"].ToString());

                        t_list.Add(t_book);
                    }
                }

                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("生产最新更新列表失败" + ex.ToString());
                return null;

            }
        }

        /// <summary>
        /// 获取首页推荐小说
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetDefaultRecommendBook()
        {
            string t_str_sql = " select * from (select top 31 t.bookid,t.bookname,t.authorname,t.description,t.categoryName,t.lastupdatechapterid,t.lastupdatechaptername,t.ChapterCount,t.lastupdatetime,t.siteId,t.siteName from tbbook t ,tbbookclick a where  t.bookId=a.bookId and t.lastupdatetime is not null order by a.clickcount desc) r order by r.lastupdatetime desc";

            List<BookInfo> t_list = new List<BookInfo>();

            BookInfo t_book = null;

            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        t_book = new BookInfo();
                        t_book.BookCategory = reader["CategoryName"].ToString().Trim().Length == 2 ? reader["CategoryName"].ToString().Trim() + "小说" : reader["CategoryName"].ToString().Trim();
                        t_book.BookId = reader["bookid"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.AuthorName = reader["authorname"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["siteId"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();
                        t_book.LastUpdateChapterId = reader["lastupdatechapterid"].ToString();
                        t_book.LastUpdateChapterName = reader["lastupdatechaptername"].ToString();
                        t_book.LastUpdateTime = reader["lastupdatetime"]==DBNull.Value?DateTime.Now: Convert.ToDateTime(reader["lastupdatetime"].ToString());
                        t_book.BookChapterCount = GetChapterCount(Convert.ToInt32(reader["chapterCount"].ToString()), reader["lastupdatechaptername"].ToString());
                        t_book.Description = reader["description"].ToString();
                        t_book.ICONUrl = string.Format("/bookICON/{0}.jpg",t_book.BookId);
                        t_list.Add(t_book);
                    }
                }
              

                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取首页推荐小说失败" + ex.ToString());
                return null;

            }

        }

        /// <summary>
        /// 获取该书同时收录的其他站点列表
        /// </summary>
        /// <param name="i_iste_id"></param>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public List<int> GetOtherSiteIdList(int i_iste_id,string i_book_name)
        {
            string t_str_sql = string.Format("select siteId from tbcrawlerbook where bookName='{0}'", i_book_name);
            List<int> t_list = new List<int>();
            int t_site_id = 0;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        if (!int.TryParse(reader["siteId"].ToString(), out t_site_id))
                            t_site_id = 0;

                        if (t_site_id != 0 && t_site_id != i_iste_id)
                        {
                            t_list.Add(t_site_id);
                        }
                    }
                }
                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说章节失败", ex);
            }
        }

        /// <summary>
        /// 获取章节信息
        /// </summary>
        /// <param name="i_site_id"></param>
        /// <param name="i_book_id"></param>
        /// <param name="i_chapter_name"></param>
        /// <returns></returns>
        public ChapterInfo GetChapterInfo(int i_site_id, long i_book_id, string i_chapter_name, out SiteInfo o_site_info)
        {
            
            o_site_info = GetTableName(i_site_id);

            if (o_site_info == null)
                return null;


            string t_str_sql = string.Format("select chapterId,chapterName,preChapterId,nextChapterId,chapterUrl,bookName from {0} where bookId={1} order by chapterId", o_site_info.TableName, i_book_id);

            ChapterInfo t_chapter = null;

            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        if (SystemUtil.CompareChapterName( reader["chapterName"].ToString(), i_chapter_name))
                        {
                            t_chapter = new ChapterInfo();
                            t_chapter.SiteId = i_site_id;
                            t_chapter.BookId = i_book_id.ToString();
                            t_chapter.BookName = reader["bookName"].ToString();
                            t_chapter.ChapterId = reader["chapterId"].ToString();
                            t_chapter.ChapterName = reader["chapterName"].ToString();
                            t_chapter.PreChapterId = reader["preChapterId"] == DBNull.Value ? "0" :reader["preChapterId"].ToString();
                            t_chapter.NextChapterId = reader["nextChapterId"] == DBNull.Value ? "0" : reader["nextChapterId"].ToString();
                            t_chapter.ChapterUrl = reader["chapterUrl"].ToString();
                            break;
                        }


                    }
                }
                return t_chapter;
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说章节失败", ex);
            }
        }

        /// <summary>
        /// 获取首页右边文字推荐
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetRightRecommendBook()
        {
            string t_str_sql = "select  t.bookid,t.bookname,t.authorname,t.lastupdatetime,t.lastUpdateChapterName,t.ChapterCount, t.siteId,t.siteName from tbbook t ,(select top 31 bookId from tbbookclick order by clickcount desc ) tb where t.bookId=tb.bookId and t.lastupdatetime is not null order by t.lastUpdateTime desc";

            List<BookInfo> t_list = new List<BookInfo>();

            BookInfo t_book = null;
            int index = 0;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        t_book = new BookInfo();
                        t_book.BookId = reader["bookid"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["siteId"].ToString());
                        t_book.LastUpdateChapterName = reader["lastupdatechaptername"].ToString();
                        t_book.BookChapterCount = GetChapterCount(Convert.ToInt32(reader["chapterCount"].ToString()), reader["lastupdatechaptername"].ToString());
                       
                        t_list.Add(t_book);
                        index++;
                        if (index == 20)
                            break;
                    }
                }

                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取首页右边文字推荐" + ex.ToString());
                return null;

            }

        }

        /// <summary>
        /// 根据最后章节名称获取章节总数
        /// </summary>
        /// <param name="i_chapter_count"></param>
        /// <param name="i_last_update_chapter_name"></param>
        /// <returns></returns>
        private int GetChapterCount(int i_chapter_count, string i_last_update_chapter_name)
        {

            string[] t_big_chinese = new string[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾", "佰", "仟", "〇" };
            string[] t_small_chinese = new string[] { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "百", "千", "〇" };
            string[] t_number = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "", "", "", "0" };

            if (string.IsNullOrEmpty(i_last_update_chapter_name))
                return i_chapter_count;

            foreach (char t_ch in i_last_update_chapter_name)
            {
                for (int index = 0; index < t_big_chinese.Length; index++)
                {
                    i_last_update_chapter_name = i_last_update_chapter_name.Replace(t_big_chinese[index], t_number[index]);
                    i_last_update_chapter_name = i_last_update_chapter_name.Replace(t_small_chinese[index], t_number[index]);
                }
            }

            Match t_mc = Regex.Match(i_last_update_chapter_name, "(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_mc != null && t_mc.Groups.Count > 1)
            {
                int t_chapter_count = 0;
                if (!int.TryParse(t_mc.Groups[1].Value.ToString(), out t_chapter_count))
                    t_chapter_count = 0;

                if (t_chapter_count != 0)
                    return t_chapter_count;
            }

            return i_chapter_count;

        }

        /// <summary>
        /// 添加图书点击
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_exist_icon"></param>
        /// <returns></returns>
        public int AddBookClick(long i_book_id, int i_exist_icon)
        {
            string t_str_sql = string.Format("select bookId from tbbookclick where bookId={0}", i_book_id);

            long t_book_id = 0;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        if (!long.TryParse(reader["bookId"].ToString(), out t_book_id))
                            t_book_id = 0;

                    }
                }

                if (t_book_id == 0)
                {
                    t_str_sql = string.Format("insert into tbbookclick(bookId,clickcount,existIcon)values({0},1,{1})", i_book_id, i_exist_icon);
                }
                else
                {
                    if (i_exist_icon == Consts.ExistsICON)
                    {
                        t_str_sql = string.Format("update tbbookclick set clickcount=clickcount+1,existIcon={0} where bookId={1}", i_exist_icon, i_book_id);
                    }
                }

                int t_ret = DBHelper.ExecuteSql(t_str_sql);

                if (i_exist_icon == (int)Consts.ExistsICON)
                {
                    t_str_sql = string.Format("update tbbook set status={0} where bookId={1}", (int)Consts.ExistsICON, i_book_id);

                    t_ret = DBHelper.ExecuteSql(t_str_sql);
                }

                return t_ret;
            }
            catch (Exception ex)
            {
                throw new DataException("添加图书点击失败", ex);
            
            }
        }
        /// <summary>
        /// 更新小说下载状态
        /// </summary>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int UpdateChapter(long i_book_id, long i_chapter_id, string i_chapter_url, BookUrlInfo i_book_url)
        {
            string t_str_sql = string.Format("update tbchapter set isDownLoad=1,chapterUrl='{0}' where chapterId={1}", i_chapter_url, i_chapter_id);

            try
            {
                if (!string.IsNullOrEmpty(i_book_url.ChapterListUrl))
                {
                    AddBookUrl(i_book_id, i_book_url.ChapterListUrl, i_book_url.SartIndex, i_book_url.StartSign, i_book_url.EndSign);
                }

                return DBHelper.ExecuteSql(t_str_sql);
            }
            catch (Exception ex)
            {
                throw new DataException("更新章节下载状态失败", ex);
            }
        }
        /// <summary>
        /// 添加小说URL
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        private int AddBookUrl(long i_book_id, string i_chapter_list_url, int i_start_index, string i_start_sign, string i_end_sign)
        {
            Uri t_u = new Uri(i_chapter_list_url);

            string t_str_sql = string.Format("select count(*) totalcount from tbbookUrl where bookId={0} and host='{1}'", i_book_id, t_u.Host);

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql);
                int t_count = 0;
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["totalcount"].ToString(), out t_count))
                        t_count = 0;
                }
                if (t_count <= 0)
                {

                    i_chapter_list_url = i_chapter_list_url.Replace("'", "''");
                    i_start_sign = i_start_sign.Replace("'", "''");
                    i_end_sign = i_end_sign.Replace("'", "''");

                    t_str_sql = string.Format("insert tbbookUrl(bookId,host,bits,chapterlisturl,startIndex,startSign,endSign)values({0},'{1}',{2},'{3}',{4},'{5}','{6}')",
                        i_book_id, t_u.Host, 1, i_chapter_list_url, i_start_index, i_start_sign, i_end_sign);

                    return DBHelper.ExecuteSql(t_str_sql);
                }
                return -1;
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加小说URL" + ex.ToString());
                return -1;
            }
        }


        /// <summary>
        /// 获取小说的章节地址列表
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public List<BookUrlInfo> GetBookUrlByBookId(long i_book_id)
        {
            string t_str_sql = string.Format("select chapterListUrl,host,bits,startIndex,startSign,endSign from tbbookUrl where bookId={0}", i_book_id);

            List<BookUrlInfo> t_list = new List<BookUrlInfo>();

            BookUrlInfo t_book_url = null;

            try
            {
                using (SqlDataReader t_reader = DBHelper.ExecuteReader(t_str_sql))
                {

                    while (t_reader.Read())
                    {

                        t_book_url = new BookUrlInfo();
                        t_book_url.BookId = i_book_id;
                        t_book_url.ChapterListUrl = t_reader["chapterListUrl"].ToString();
                        t_book_url.Host = t_reader["host"].ToString();
                        t_book_url.Bits = int.Parse(t_reader["bits"].ToString());
                        t_book_url.SartIndex = t_reader["startIndex"] == DBNull.Value ? 0 : Convert.ToInt32(t_reader["startIndex"].ToString());
                        t_book_url.StartSign = t_reader["startSign"] == DBNull.Value ? "" : t_reader["startSign"].ToString();
                        t_book_url.EndSign = t_reader["endSign"] == DBNull.Value ? "" : t_reader["endSign"].ToString();
                        t_list.Add(t_book_url);
                    }
                }
                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说章节地址", ex);
            }

           
        }

          /// <summary>
        /// 添加小说URL
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public int AddBookUrl(BookUrlInfo i_book_url)
        {
            string t_str_sql = string.Format("select count(*) totalcount from tbbookUrl where bookId={0} and host='{1}'", i_book_url.BookId, i_book_url.Host);

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql);
                int t_count = 0;
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["totalcount"].ToString(), out t_count))
                        t_count = 0;
                }

                i_book_url.ChapterListUrl = i_book_url.ChapterListUrl.Replace("'", "''");
                i_book_url.StartSign = i_book_url.StartSign.Replace("'", "''");
                i_book_url.EndSign = i_book_url.EndSign.Replace("'", "''");

                if (t_count > 0)
                {
                    t_str_sql = string.Format("update tbbookUrl set bits={0},startIndex={1},startSign='{2}',endSign='{3}' where bookId={4} and host='{5}'", i_book_url.Bits, i_book_url.SartIndex, i_book_url.StartSign, i_book_url.EndSign, i_book_url.BookId, i_book_url.Host);
                }
                else
                {

                    t_str_sql = string.Format("insert tbbookUrl(bookId,host,bits,chapterlisturl,startIndex,startSign,endSign)values({0},'{1}',{2},'{3}',{4},'{5}','{6}')",
                        i_book_url.BookId, i_book_url.Host, i_book_url.Bits, i_book_url.ChapterListUrl, i_book_url.SartIndex, i_book_url.StartSign, i_book_url.EndSign);
                }

                return DBHelper.ExecuteSql(t_str_sql);
            }
            catch (Exception ex)
            {
                throw new Exception("添加小说URL失败" + ex.ToString());

            }
        }

    }
}
